import { getMainWindow } from '$main/windows/main-window';
import { Tray, nativeImage, Menu, BrowserWindow } from 'electron';
import type { MenuItemConstructorOptions } from 'electron';
import path from 'node:path';
import { showMainWindow } from '../windows/main-window';
import { appTitle } from '#common/configs/build-const';
import { createChildWindow } from '$main/windows/child-window';
import log from '$main/utils/logger';

let tray: Tray | null = null;

function createMenu() {
  if (!tray) {
    return;
  }
  BrowserWindow;
  const menu: MenuItemConstructorOptions[] = [
    {
      label: '设置',
      click: () => {
        const mainWin = getMainWindow();
        if (!mainWin || mainWin.getChildWindows().some((x) => x.title == '设置')) return;

        createChildWindow(mainWin, {
          title: '设置',
          width: 550,
          height: 450,
          url: '/setting'
        });
      }
    },
    {
      label: '打开创意魔方',
      click: () => {
        showMainWindow();
      }
    },
    {
      label: '退出创意魔方',
      role: 'quit'
    }
  ];

  const contextMenu = Menu.buildFromTemplate(menu);
  return contextMenu;
}

export function createTray() {
  if (tray) {
    return;
  }

  const iconPath = path.join(__dirname, '../../resources/icons/tray', 'icon.png');
  tray = new Tray(nativeImage.createFromPath(iconPath));
  tray.setToolTip(appTitle);

  const contextMenu = createMenu();
  tray.setIgnoreDoubleClickEvents(true);

  tray.on('click', () => {
    //tray!.setContextMenu(null);
    showMainWindow();
  });

  tray.on('right-click', () => {
    if (!contextMenu) {
      return;
    }
    //tray!.setContextMenu(contextMenu);
    tray!.popUpContextMenu(contextMenu);
  });
}

export function destroyTray() {
  if (!tray) {
    return;
  }
  tray.destroy();
  tray = null;
}

export function getTray() {
  return tray;
}
